
module.exports = function(app, config) {

  var express = require('express');
  var expressValidator = require('express-validator');
  var morgan  = require('morgan');// express3 loger
  var methodOverride = require('method-override') //
  var compression = require('compression');
  var bodyParser = require('body-parser')// json, body, urlencode
  var cookieParser = require('cookie-parser');
  var session = require('express-session')
  var errorHandler = require('errorhandler')
  var favicon = require('serve-favicon');

  var MongoStore = require('connect-mongo')(session);

  var db = require('./config.db');


  // var csrf    = require('csurf');

  // var flash = require('connect-flash');

  var passport = require('./config.auth')(config);

  app.set('views', config.rootPath + '/server/views');
  app.set('view engine', 'jade');
  app.set('port', config.port );
  app.set('env', config.env );

  app.use(compression({
    threshold: 512
  }))
  // enable HTTP verbs such as PUT or DELETE
  // must before any module that needs to know the method of the request (for example, it must be used prior to the csurf module).
  app.use(methodOverride('X-HTTP-Method-Override')) // 
  app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // json
  app.use(bodyParser.urlencoded());
  
  // app.use(csrf())


  app.use(cookieParser( config.cookie_secret ));

  app.use(session({
      secret: config.cookie_secret,
      store: new MongoStore({
          mongoose_connection : db.connection,
      })
  }));

  // app.use(flash());

  app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // json
  app.use(bodyParser.urlencoded());
  
  // file upload---------------
  app.use(bodyParser({ keepExtensions: true, uploadDir: config.rootPath+'/uploads' }));

  // auth
  app.use(passport.initialize());
  app.use(passport.session());

  app.use(favicon(config.rootPath + '/public/favicon.png'));
  app.use(express.static(config.rootPath + '/public'));


  // development only
  if ('development' == config.env ) {
    app.use(morgan('dev'))// app.use(express.logger('dev'));
    app.use(errorHandler());
  }

  // for routes to use validator and passport
  // app.flash = flash;
  app.validator = expressValidator;
  app.passport= passport;

}